/**
 * 文件操作扩展方法
  */
import axios from 'axios';
import request from '@/lib/request';
import qs from 'qs';
import { getLocalToken, getLocalTokentype } from '@/lib/auth';
import { getLocale } from '@/lib/lang';

/**
 * 下载文件
 * @param {string} fileUrl 下载请求地址
 * @param {string} fileName 下载文件名称 如 测试文件.doc
 * @param {string} baseURL 接口前缀 如 WEB_CONFIG.VUE_APP_SWAGGER_TRAIN_BASE
 */
export function api_GET_DownLoadFileAddHeader (fileUrl, fileName, params, baseURL) {
  const url = baseURL || WEB_CONFIG.VUE_APP_SWAGGER_GAME_BASE;
  return new Promise((resolve, reject) => {
    request({
      url: url + fileUrl,
      method: 'get',
      responseType: 'blob',
      params: params
    }).then(res => {
      var blob = new Blob([res]);
      if ('msSaveOrOpenBlob' in navigator) {
        window.navigator.msSaveOrOpenBlob(blob, fileName);
        return;
      }
      const downloadElement = document.createElement('a');
      const href = window.URL.createObjectURL(res);
      const key = fileName ? fileName.lastIndexOf('.') : null;
      const str = fileName.substr(key);
      if (str === '.pdf') {
        window.open(href);
      } else {
        downloadElement.style.display = 'none';
        downloadElement.href = href;
        downloadElement.download = fileName;
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement);
        window.URL.revokeObjectURL(href);
      }
      resolve(true);
    }, error => {
      reject(error);
    });
  });
}

/**
 * 上传文件
 * @param {string} fileUrl 上传文件地址
 * @param {string} afileData 文件数据
 * @param {object} aQueryData 地址上数据
 */
export function api_Post_UploadFileAddHeader (aUrl, afileData, aQueryData) {
  return new Promise((resolve, reject) => {
    const form = new FormData();
    form.append('formFile', afileData);
    const token = getLocalToken();
    const config = {
      headers: {
        Authorization: (getLocalTokentype() ? getLocalTokentype() : 'Bearer') + ' ' + token,
        'Accept-Language': getLocale() === 'en' ? 'en' : 'zh-Hans'
      },
      baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
      // withCredentials: true, // send cookies when cross-domain requests
      timeout: 600000, // request timeout
      paramsSerializer: (params) => {
        return qs.stringify(params);
      },
      params: aQueryData || null
    };
    axios.post(aUrl, form, config).then(res => {
      if (res.status === 200) {
        resolve(res.data);
      } else {
        reject(res.data);
      }
    }).catch(
      error => {
        reject(error);
      }
    );
  });
}
